<template>
  <div class="clearfix">
    <a-upload
      action="/api/file/upload"
      name="fileList"
      list-type="picture-card"
      :multiple="multiple"
      :file-list="fileList"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < maxLength">
        <a-icon type="plus" />
        <div class="ant-upload-text">点击上传</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
export default {
  name: 'UploadImg',
  props: {
    maxLength: {
      type: Number,
      default: 1,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    value: {
      type: String,
    },
  },
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: [],
    }
  },
  watch: {
    // 监听数据变化，及时提交给父组件
    fileList: {
      deep: true,
      immediate: true,
      handler: function (newV, oldV) {
        if (oldV!=undefined) {
          this.fileList = newV
          let temp = this.fileList.map((item) => item.url)
          // 向父组件更新
          if (temp.length > 0) {
            let imgs = this.maxLength == 1 ? temp.join(',') : temp
            this.$emit('change', imgs)
          } else {
            this.$emit('change', this.maxLength == 1 ? '' : [])
          }
        }
      },
    },
    // 监听父组件传递过来的图片列表信息
    value: {
      deep: true,
      immediate: true,
      handler: function (newV) {
        console.log(newV)
        if(newV){
          let arr = newV.split(',')
          this.fileList=arr.map((item,index)=>({url:item,uid:index,name:item}))
        }
      },
    },
  },
  methods: {
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange({ file, fileList }) {
      if (file.status == 'uploading') {
        this.fileList = fileList
      }
      if (file.status === 'done') {
        this.changeList(fileList)
      }
      if (file.status == 'removed') {
        this.changeList(fileList)
      }
    },
    changeList(list) {
      let arr = []
      list.forEach((item) => {
        if (item.response) {
          let obj = { ...item }
          obj.url = item.response.data
          arr.push(obj)
        } else {
          arr.push(item)
        }
      })
      this.fileList = arr
    },
    getImgs(arr) {
      let imgList = []
      if (arr.length > 0) {
        imgList = arr.map((item) => item.url)
        return imgList.join(',')
      } else {
        return ''
      }
    },
  },
}
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
